package thread_pools;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @Author liangzai
 * @Description:
 */
public class MyThreadPools {
    private int n;
    private BlockingQueue<Runnable> queue;
    private Object locker = new Object();

    public MyThreadPools(int n){
        queue = new ArrayBlockingQueue<>(1000);
        for (int i = 0; i < n; i++) {
            Thread thread = new Thread(()->{
                while(true){
                    try {
                        queue.take().run();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
        }
    }

    public void submit(Runnable runnable){
        synchronized (locker){
            queue.add(runnable);
        }
    }
}

class Main{
    public static void main(String[] args) throws InterruptedException {
        MyThreadPools threadPools = new MyThreadPools(4);
        Thread thread = new Thread(()->{
            for (int i = 0; i <= 100; i++) {
                int id = i;
                threadPools.submit(()->{
                    System.out.println(Thread.currentThread()+" "+id);
                });
            }
        });
        thread.start();
        thread.join();
    }
}
